package com.serookie.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.serookie.dto.OrderGoods;
import com.serookie.entity.*;
import com.serookie.service.AddressService;
import com.serookie.service.GoodsService;
import com.serookie.service.Impl.OrderServiceImpl;
import com.serookie.service.OrderDetailsService;
import com.serookie.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author kevintam
 * @version 1.0
 * @date 2021/5/31 20:00
 */
@RestController
@RequestMapping("/wx/order")
@Api(value="订单接口",tags={"订单接口"})
public class OrderController{

    @Autowired
    private OrderService orderService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private OrderDetailsService detailsService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/all")
    @ApiOperation("查询所有的订单")
    public Result all(){
        List<Order> all = orderService.all();
        return Result.ok().message("查询成功").data("all",all);
    }
    @PostMapping("/del/{orderId}")
    @ApiOperation("根据id进行删除订单")
    public Result delId(@PathVariable("orderId") Integer orderId){
        Boolean flag = orderService.deleteOrder(orderId);
        if(flag){
            return Result.ok().message("操作成功");
        }
        return Result.error().message("操作失败");
    }
    @GetMapping("/{status}")
    @ApiOperation("根据订单状态查询订单")
    public Result getPayStatus(@PathVariable("status")Integer payStatus){
        List<Order> payStatus1 = orderService.getPayStatus(payStatus);
        return Result.ok().message("操作成功").data("data",payStatus1);
    }
    /**
     * 模糊查询
     * @param userId
     * @return
     */
    @GetMapping("/info")
    @ApiOperation("根据userId进行查询订单")
    public Result OrderByUserId(Integer userId){
        List<Order> orders = orderService.OrderByUserId(userId);
        return Result.ok().message("查询成功").data("data",orders);
    }
    @GetMapping("/count")
    @ApiOperation("查询所有的商品记录数")
    public Result count(){
        Integer integer = orderService.goodsCount();
        return Result.ok().message("操作成功").data("count",integer);
    }
    /**
     * 模糊查询
     * @param orderNumber
     * @return
     */
    @GetMapping("/getOrder")
    @ApiOperation("根据userId进行查询订单")
    public Result getOrder(String orderNumber){
        List<Order> order = orderService.getOrder(orderNumber);
        return Result.ok().message("查询成功").data("data",order);
    }
    /**
     * 新增商品
     * @param
     * @return
     */
    @PostMapping("/save")
    @ApiOperation("新增订单")
    public Result save(@RequestParam("userName")String userName,
                       @RequestParam("orderPrice") BigDecimal orderPrice,
                       @RequestParam("phone")String phone,
                       @RequestParam("postalCode")String postalCode,
                       @RequestParam("addressAll") String addressAll,
                       @RequestParam("orderGoods") String orderGoods
                       ){
        List<OrderGoods> orderGoods2 = JSON.parseArray(orderGoods, OrderGoods.class);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        SysUser details = (SysUser)authentication.getPrincipal();
        String openid=details.getOpenid();
        Address flag = addressService.getById(openid);
        if(flag==null){
            Address address = new Address();
            address.setName(userName);
            address.setPhone(phone);
            address.setAddress(addressAll);
            address.setPostalCode(postalCode);
            address.setOpenid(openid);
            //将地址插入到数据库中
            Boolean aBoolean = addressService.addAddress(address);
        }
        //生成订单信息
        Order order = new Order();
        Address address = addressService.getById(openid);
        order.setAddressId(address.getId());
        order.setOrderPrice(orderPrice);
        //1表示支付成功
        order.setOpenid(openid);
        order.setPayStatus(1);
        //订单号采用时间戳的方式,正式项目不可使用

        DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format = sdf.format(new Date());
        order.setOrderNumber(format);
        System.out.println(order);
        Boolean aBoolean = orderService.addOrder(order);
        if(aBoolean){
            //订单金额
            OrderDetails orderDetails = new OrderDetails();
            //订单的详细信息
            for (OrderGoods orderGoods1:orderGoods2
            ) {
                orderDetails.setGoodsId(orderGoods1.getGoodsId());
                orderDetails.setNum(orderGoods1.getNum());
                orderDetails.setPrice(orderGoods1.getGoodsPrice());
                Order order1 = orderService.OrderByNumber(format);
                orderDetails.setOrderId(order1.getOrderId());
                detailsService.addOrderDetails(orderDetails);
            }
        }
        return Result.ok().message("查询成功");
    }
    /**
     * 修改商品分类
     * @param order
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("修改订单")
    public Result update(Order order){
        boolean flag = orderService.updateOrder(order);
        if(flag){
            return Result.ok().message("修改成功");
        }
        return Result.error().message("修改失败");
    }
}
